package com.example.interceptors;

import com.example.utils.JwtHelper;
import com.example.utils.Result;
import com.example.utils.ResultCodeEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author: Yun
 * @Date: 2024/3/15
 */
@Component
public class LoginProtectedInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtHelper jwtHelper;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求中获取token
        String token = request.getHeader("token");
        // 检查是否有效
        boolean expiration = jwtHelper.isExpiration(token);
        // 有效
        if (!expiration) return true;
        // 无效 返回504
        Result result = Result.build(null, ResultCodeEnum.NOTLOGIN);
        // 手动写回响应 使用 ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        String res = objectMapper.writeValueAsString(result);
        response.getWriter().print(res);
        return false;
    }
}
